<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{
            width: 100px;
            height: 100px;
            background-color: #f00;
        }
    </style>
</head>
<body>
    <div id="app">
        <div id="box" v-drag></div>
    </div>
    <script src='vue.js'></script>
    <script>
        /*
            Vue.directive(指令名称,指令配置对象)全局注册一个指令
        */
        Vue.directive('drag',{
            /*inserted,指令被添加到元素上时执行的函数(指令初始化函数)*/
            inserted:function(el){
                el.style.position = 'relative'
                el.onmousedown = function(e){
                    // 记录点击的坐标
                    el.startX = e.pageX
                    el.startY = e.pageY
                    // 记录元素当前所在的位置
                    // el.elx = parseInt(el.style.left)
                    // el.ely = parseInt(el.style.top)
                    el.elx = el.offsetLeft
                    el.ely = el.offsetTop
                    window.onmousemove = function(ev){
                        // 当前鼠标点距离点击点的偏移量
                        var xoff = ev.pageX - el.startX
                        var yoff = ev.pageY - el.startY
                        // 计算元素现在的位置
                        var x = el.elx + xoff
                        var y = el.ely + yoff
                        el.style.left = x + 'px'
                        el.style.top = y + 'px'
                    }
                }
                window.onmouseup = function(){
                    window.onmousemove = null
                }
            }
        })
        new Vue({
            el:'#app',
        })
    </script>
</body>
</html>